<template>
  <navbar :showLeft="false" title="AI模拟面试"></navbar>
  <view class="header" :style="{paddingTop: appInfoStore.getInfo().navBarHeight + 2*appInfoStore.getInfo().statusBar + 'px'}"></view>
  <view class="user-page">
    <!-- 头部信息区域 -->
    <view class="header-container">
      <view class="avatar-box">
        <image
          class="avatar"
          :src="userInfo.avatarUrl"
          mode="aspectFill"
        />
        <view class="user-basic">
          <view class="username">用户昵称：{{userInfo.nickname||未知}}</view>
          <view class="desc">创建时间：{{userInfo.createdAt||未知}}</view>
        </view>
      </view>
      <view class="stats-row">
        <view class="stat-item">
          <view class="stat-value">{{ userInfo.interviewCount||0 }}</view>
          <view class="stat-label">面试次数</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ userInfo.maxScore||0 }}</view>
          <view class="stat-label">最高分</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ userInfo.avgScore||0 }}</view>
          <view class="stat-label">平均分</view>
        </view>
      </view>
      <view class="btn-group">
        <button class="btn btn-view" @click="goToHistory">查看历史</button>
        <button class="btn btn-start" @click="startNewInterview">开始新面试</button>
      </view>
    </view>

    <!-- 最近面试区域 -->
    <view class="recent-interview">
      <view class="section-title">最近面试</view>
      <view v-if="latestInterviewInfo.length > 0">
        <view
          v-for="(item, index) in latestInterviewInfo"
          :key="index"
          class="interview-card"
          @click="goToReport(item)"
        >
          <view class="card-content">
            <view class="interview-header">
              <view class="interview-type">{{ item.title }}</view>
              <view class="interview-score">得分: {{ item.score||0 }}</view>
            </view>
            <view class="interview-time">时间: {{ formatTime(item.startTime) }}</view>
          </view>
        </view>
        <button class="btn clear-btn" @click="handleClearHistory">
          清除所有历史记录
        </button>
      </view>
      <view v-else class="no-interview">
        暂无面试记录 <span class="go-interview" @click="startNewInterview">去面试</span>
      </view>
    </view>
  </view>
</template>

<script setup>
const appInfoStore = useAppInfoStore();
import { useAppInfoStore } from "@/stores/appInfo";
import { onShow } from "@dcloudio/uni-app";
import { ref, reactive, getCurrentInstance, nextTick,computed  } from "vue"
const { proxy } = getCurrentInstance();
const interviews = ref([
  { type: '技术面试', score: 85, question: '简述CSS盒模型' },
  { type: '技术面试', score: 93, question: '简述CSS盒模型' }
])

const goToHistory = () => {
  uni.navigateTo({
    url: '/pages/history/HistoryIndex'
  });
}

const startNewInterview = () => {
  uni.switchTab ({
    url: '/pages/category/CategoryIndex'
  });
}

const goToReport = (item) => {
  uni.navigateTo({
    url: `/pages/report/InterviewReport?interviewId=${item.interviewId}`
  });
};

const interviewStats = computed(() => {
  const count = interviews.value.length
  const scores = interviews.value.map((item) => item.score)
  const highestScore = scores.length > 0 ? Math.max(...scores) : 0
  const avgScore =
    scores.length > 0
      ? (scores.reduce((sum, score) => sum + score, 0) / count).toFixed(1)
      : 0

  return {
    count,
    highestScore,
    avgScore
  }
})

// 清除历史记录
const handleClearHistory = async () => {
  uni.showModal({
    title: '提示',
    content: '确定要清除所有历史记录吗？此操作不可恢复',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '删除中...',
            mask: true
          });
          
          // 调用删除接口
          const result = await proxy.Request({
            url: proxy.Api.deleteHistory,
            method: 'POST',
            showLoading: false
          });
          
          if (result) {
            dataSource.value = [];
            uni.showToast({
              title: '历史记录已清除',
              icon: 'success'
            });
          }
        } catch (error) {
          console.error('删除失败:', error);
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};



//加载个人信息
const userInfo=ref({
  nickname:"chenyf",
  avatarUrl:"http://localhost:9096/user/file/getImage/avatar_img/pic1.png",
  createdAt:"2025-12-1"
});
const loadPersonInfo=async()=>{
    const result = await proxy.Request({
        url: proxy.Api.getRecordInfo,
        method: 'GET',
        showLoading: false
      });
      if(!result){
        return;
      }
      Object.assign(userInfo.value,result)
}

// 加载个人最近面试信息
const latestInterviewInfo=ref([{}]);
const loadLatestInterviewInfo=async()=>{
    const result = await proxy.Request({
        url: proxy.Api.getLatestInterviewInfo,
        method: 'GET',
        showLoading: false
      });
      if(!result){
        return;
      }
      latestInterviewInfo.value=result;
}
// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '未知时间';
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}
const loadUserInfo=async()=>{
    const result = await proxy.Request({
        url: proxy.Api.getUserInfo,
        method: 'GET',
        showLoading: false
      });
      if(!result){
        return;
      }
      userInfo.value.nickname=result.nickname;
      userInfo.value.avatarUrl=proxy.Api.domain+proxy.Api.imageUrl+result.avatarUrl;
}

onShow(()=>{
  loadPersonInfo();
  loadLatestInterviewInfo();
  loadUserInfo();
})



</script>

<style scoped>
.user-page {
  background-color: #f5f7fa;
  /* min-height: 100vh; */
  padding: 16px;
  padding-bottom: 60px;
}

/* 头部区域 */
.header-container {
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
}

.avatar-box {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.user-basic {
  margin-left: 12px;
}

.username {
  font-size: 18px;
  font-weight: 600;
  color: #1f2329;
}

.desc {
  font-size: 14px;
  color: #86909c;
  margin-top: 2px;
}

/* 统计数据 */

.no-interview {
  text-align: center;
  padding: 20px;
  color: #86909c;
  background: #fff;
  border-radius: 8px;
}
.go-interview {
  color: #0282ee;
  text-decoration: underline;
  margin-left: 5px;
}
.interview-time {
  font-size: 12px;
  color: #86909c;
  margin-top: 8px;
}




.stats-row {
  display: flex;
  justify-content: space-around;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f2f3f5;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #0282ee;
}

.stat-label {
  font-size: 12px;
  color: #86909c;
  margin-top: 4px;
}

/* 按钮样式 */
.btn-group {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.btn {
  padding: 10px 0;
  border-radius: 4px;
  font-size: 14px;
  border: 1px solid transparent;
  width: 170px;
}

.btn-view {
  background: #fff;
  color: #0282ee;
  border-color: #0282ee;
}

.btn-start {
  background: #0282ee;
  color: #fff;
}

/* 清除按钮样式 */
.clear-btn {
  width: 100%;
  padding: 12px 0;
  border-radius: 8px;
  background: #fff;
  color: #ff4d4f;
  border: 1px solid #ff4d4f;
  margin-top: 12px;
}

/* 最近面试区域 */
.recent-interview {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2329;
  margin-bottom: 12px;
}

.interview-card {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-radius: 10px;
  padding: 14px;
  margin-bottom: 12px;
}

.card-content {
  display: flex;
  flex-direction: column;
}

.interview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.interview-type {
  font-size: 14px;
  font-weight: 500;
  color: #1f2329;
}

.interview-score {
  font-size: 12px;
  color: #86909c;
}

.interview-question {
  background-color: #f0f1f4;
  margin-top: 8px;
  line-height: 1.5;
  padding: 6px;
  border-radius: 4px;
}

.question {
  font-size: 13px;
  color: #4e5969;
}

/* 自定义底部导航栏样式 */
.custom-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 10px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.tabbar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px 10px;
  color: #666;
}

.tabbar-item .icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.tabbar-item .text {
  font-size: 12px;
}

.tabbar-item.active {
  color: #0282ee;
}
</style>